//
//  BanBu_SetAvatarViewController.m
//  BanBu
//
//  Created by jie zheng on 12-7-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BanBu_SetAvatarViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "BanBu_AppDelegate.h"
#import "TKLoadingView.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "UIImageView+WebCache.h"
#import "BanBu_LocationManager.h"
#import "BanBu_ImageView.h"
#import "BanBu_NavButton.h"
#import "SFHFKeychainUtils.h"
#import "UIViewController+Animation.h"

@interface BanBu_SetAvatarViewController ()
{
    int selectIndex;
}
@end

@implementation BanBu_SetAvatarViewController
@synthesize imagePathExtension = _imagePathExtension;

- (id)initWith
{
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    _useDefaultImage = NO;
    selectIndex = -1;
    self.view.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    
    BanBu_NavButton *backButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    backButton.position = ButtonPositionLeft;
    backButton.frame=CGRectMake(0, 0, 60, 30);
    [backButton addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
    [backButton setTitle:@"＜4/5" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize:18];
    UIBarButtonItem *back = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
    self.navigationItem.leftBarButtonItem = back;
    [backButton release];
    
    CGFloat btnLen = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 30)].width;
    self.navigationItem.leftBarButtonItem.title = @"＜4/5";
    
    
     BanBu_NavButton *nextButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    nextButton.position = ButtonPositionRight;
    nextButton.frame=CGRectMake(0, 0, btnLen+20, 30);
    [nextButton addTarget:self action:@selector(complete:) forControlEvents:UIControlEventTouchUpInside];
    [nextButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
//    nextButton.titleLabel.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:18];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:18];
    UIBarButtonItem *next = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];
    self.navigationItem.rightBarButtonItem = next;
    [nextButton release];
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    
    UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 130, 130)];
    bkView.backgroundColor = [UIColor whiteColor];
    bkView.layer.borderColor = [[UIColor grayColor] CGColor];
    bkView.layer.borderWidth = 1.0;
    bkView.layer.cornerRadius = 6.0f;
    [self.view addSubview:bkView];
    [bkView release];
    
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 110, 110)];
    _avatorView = imageview;
    imageview.image = [UIImage imageNamed:@"default.png"];
    [bkView addSubview:imageview];
    [imageview release];
    
    UIButton *btnXiangCe = [UIButton buttonWithType:UIButtonTypeCustom];
    btnXiangCe.frame = CGRectMake(165, 20, 130, 65);
    [btnXiangCe setBackgroundImage:[UIImage imageNamed:@"button_reggallery.png"] forState:UIControlStateNormal];
    [btnXiangCe setTitleEdgeInsets:UIEdgeInsetsMake(35, 0, 10, 0)];
    [btnXiangCe setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnXiangCe.titleLabel.font = [UIFont systemFontOfSize:13];
    [btnXiangCe setTitle:NSLocalizedString(@"btnXiangCe", nil) forState:UIControlStateNormal];
    [btnXiangCe addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    btnXiangCe.tag = 1;
    [self.view addSubview:btnXiangCe];
    
    UIButton *btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCamera.frame = CGRectMake(165, 85, 130, 65);
    [btnCamera setBackgroundImage:[UIImage imageNamed:@"button_regtake.png"] forState:UIControlStateNormal];
    [btnCamera setTitleEdgeInsets:UIEdgeInsetsMake(35, 0, 10, 0)];
    [btnCamera setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnCamera.titleLabel.font = [UIFont systemFontOfSize:13];
    [btnCamera setTitle:NSLocalizedString(@"btnCamera", nil) forState:UIControlStateNormal];
    [btnCamera addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    btnCamera.tag = 2;
    [self.view addSubview:btnCamera];
    
    
    
    
    
    CGSize size = [NSLocalizedString(@"warningLabel1", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
    
    UIView *roundView = [[UIView alloc] initWithFrame:CGRectMake(10, 210, 300, 42+size.height)];
    roundView.layer.cornerRadius = 8.0;
    roundView.layer.borderWidth = 0.8;
    roundView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    roundView.backgroundColor = [UIColor whiteColor];
    
    UILabel *tipLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 20)];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.textAlignment = kTextAlignmentCenter;
    tipLabel.textColor = [UIColor blackColor];
    tipLabel.font = [UIFont boldSystemFontOfSize:16];
    tipLabel.text = NSLocalizedString(@"helpfulTitle", nil);
    [roundView addSubview:tipLabel];
    [tipLabel release];
    

    UILabel *helpLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 300, size.height)];
    helpLabel.backgroundColor = [UIColor clearColor];
    helpLabel.textAlignment = kTextAlignmentCenter;
    helpLabel.numberOfLines = 10;
    helpLabel.textColor = [UIColor darkGrayColor];
    helpLabel.font = [UIFont boldSystemFontOfSize:16];
    helpLabel.text = NSLocalizedString(@"warningLabel1", nil);
    [roundView addSubview:helpLabel];
    [helpLabel release];
    [self.view addSubview:roundView];
    [roundView release];
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [AppComManager cancalHandlesForObject:self];
    UILabel *lab = (UILabel *)[self.navigationController.navigationBar viewWithTag:10000];
    [lab removeFromSuperview];
    UILabel *lab1 = (UILabel *)[self.navigationController.navigationBar viewWithTag:10001];
    [lab1 removeFromSuperview];
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:YES];
    /*
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
    lab.text = [NSString stringWithFormat:@"%@(5/5)",NSLocalizedString(@"avatarTitle", nil)];
    lab.lineBreakMode = kTextLineBreakByWordWrapping;
    [self.navigationController.navigationBar addSubview:lab];
    lab.center = CGPointMake(self.navigationController.navigationBar.frame.size.width/2, 22);
    lab.textAlignment = kTextAlignmentCenter;
    CGFloat height = [lab.text sizeWithFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:18] constrainedToSize:CGSizeMake(150, 44) lineBreakMode:kTextLineBreakByWordWrapping].height;
    lab.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:height>21?15:18];
    //    lab.adjustsFontSizeToFitWidth = YES;
    lab.backgroundColor = [UIColor clearColor];
    lab.numberOfLines = 2;
    lab.textColor = [UIColor whiteColor];
    lab.tag = 10000;
    [lab release];
     */
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160,22)];
    lab.text = NSLocalizedString(@"avatarTitle", nil);
    lab.lineBreakMode = kTextLineBreakByTruncatingTail;
    [self.navigationController.navigationBar addSubview:lab];
    lab.center = CGPointMake(160, 11);
    lab.textAlignment = kTextAlignmentCenter;
    lab.backgroundColor = [UIColor clearColor];
    lab.textColor = [UIColor whiteColor];
    lab.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:15];
    lab.tag = 10000;
    [lab release];
    
    
    UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 22)];
    lab1.center = CGPointMake(160, 33);
    lab1.text = @"(5/5)";
    [self.navigationController.navigationBar addSubview:lab1];
    lab1.textAlignment = kTextAlignmentCenter;
    lab1.backgroundColor = [UIColor clearColor];
    lab1.textColor = [UIColor whiteColor];
    lab1.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:15];
    lab1.tag = 10001;
    [lab1 release];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.hidesBackButton = YES;

}

- (void)btnAction:(UIButton *)button
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    if(button.tag == 1)
    {
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypePhotoLibrary]) {
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }
    else 
    {        
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;        
    }
    [picker setAllowsEditing:YES];
    [self presentViewController:picker animated:YES];
    [picker release];

    
}

#pragma mark  -
- (void)imagePickerController:(UIImagePickerController *)picker 
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {
    
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        self.imagePathExtension = @"jpg";
    else
    {
        self.imagePathExtension = [[[editingInfo valueForKey:UIImagePickerControllerReferenceURL] pathExtension] lowercaseString];
        if([self.imagePathExtension isEqualToString:@"gif"])
            self.imagePathExtension = @"jpg";
    }
    
    //NSLog(@"geshi:%@",_imagePathExtension);
    
    _picked = YES;
    _avatorView.image = image;
    [picker dismissViewControllerAnimated:YES];    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES];
}

/*//提交用户个人照片BASE64版 以post形式提交，文件先经base64编码
 网址　http://www.koochat.com/_user_login/_base64_user_face.php?phone=y&loginid=xxxxxxx&photofile=xxxxxxx
 参数　{"fc":"base64_user_face","loginid":"20120707221438-28D8AD6E-569E-677F-2385-6DBCD987FF31","phone":"y","photofile":"eyJmYyI6InNldF91c2VyX2xvY2F0aW9uIiwibG9naW5pZCI6IjIw"}
 返回　{"fc":"base64_user_face","ok":"y"}
 
 loginid值为登录ID
 phone值为y表示来自手机客户端
 photofile值为经过base64编码后的文件
 ok值为y表示设置成功，值为n表示设置失败
 *头像为高宽相等的正方形，限10k-200K，超200K则保持高宽比例缩小到200K以内*/

//- (void)complete:(UIButton *)button
//{
//    if(!_picked)
//    {
////        [TKLoadingView showTkloadingAddedTo:self.view title:@"请选择头像" activityAnimated:NO duration:1.5];
//        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 180) title:NSLocalizedString(@"selectAvater", nil) activityAnimated:NO duration:1.0];
//
//        return;
//    }
//    
//    NSData *data = nil;
////    if([self.imagePathExtension isEqualToString:@"png"])
////        data = UIImagePNGRepresentation(_avatorView.image);
////    else
//        data = UIImageJPEGRepresentation(_avatorView.image, 0.5);
//    NSLog(@"注册时头像的大小%d",data.length);
//    NSMutableDictionary *uploadDic = [NSMutableDictionary dictionary];
//    [uploadDic setValue:@"y" forKey:@"phone"];
//    [uploadDic setValue:@"jpg" forKey:@"picformat"];
//    self.navigationController.view.userInteractionEnabled = NO;
//    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendAvater", nil) activityAnimated:YES];
//    [AppComManager uploadRegAvatarImage:data Par:uploadDic delegate:self];
//    
//}
#pragma mark 上传注册头像参数 图片Data "picformat"  "phone"最后一个参数作用不知
-(void)uploadAvatarImage:(UIImage *)_image
{
    NSData *data = nil;
    data = UIImageJPEGRepresentation(_image, 0.5);
    NSMutableDictionary *uploadDic = [NSMutableDictionary dictionary];
    [uploadDic setValue:@"y" forKey:@"phone"];
    [uploadDic setValue:@"jpg" forKey:@"picformat"];
    [AppComManager uploadRegAvatarImage:data Par:uploadDic delegate:self];
}
-(void)complete:(UIButton *)button
{
    if(_picked)
    {
        [self uploadAvatarImage:_avatorView.image];
        self.navigationController.view.userInteractionEnabled = NO;
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendAvater", nil) activityAnimated:YES];
    }
    else if(_useDefaultImage)
    {
        NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
        [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
        [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
        [registerInfo setValue:[self getFacePath:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefile"]] forKey:@"facepath"];
        [registerInfo setValue:[self getFaceName:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefile"]] forKey:@"facefile"];
        [registerInfo setValue:[self getFaceName:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefull"]] forKey:@"facefull"];
        [self saveRegister:registerInfo];
        
        UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"waitauditNotice", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
        alert.tag = 2;
        [alert show];
        [alert release];
    }
    else
    {
        
        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 180) title:NSLocalizedString(@"selectAvater", nil) activityAnimated:NO duration:1.0];
        
        return;
    }

    
}
#pragma mark -注册信息保存到MyAppDataManager 需要参数 “plat” “plong” “facepath” “facefile” “facefull”
-(void)saveRegister:(NSDictionary *)_registerInfo
{
    [MyAppDataManager.regDic addEntriesFromDictionary:_registerInfo];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        if(alertView.tag == 1){
            [self performSelector:@selector(complete:)];

        }
    }else{
        if(alertView.tag == 2){
            
            [MyAppDataManager.regDic setValue:[UserDefaults valueForKey:@"pushid"] forKey:@"pushid"];
            [self registerUserWith:MyAppDataManager.regDic];
            self.navigationController.view.userInteractionEnabled =NO;
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"registering", nil) activityAnimated:YES];
        }
    }
}
#pragma mark - 注册用户 提交所有注册资料 存储在MyAppDataManager中的另添加设备号 "deviceid" 和推送号 “pushid”
-(void)registerUserWith:(NSMutableDictionary *)_registerInfo
{
    NSError *error;
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
    {
        [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
    }
    //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
    BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if(ap.pushid&&ap.pushid.length)
    {
        [_registerInfo setValue:ap.pushid forKey:@"deviceid"];
    }
    else
    {
        NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
        [_registerInfo setValue:systemUDID forKey:@"deviceid"];
    }

    [AppComManager getBanBuData:BanBu_Set_Register_User par:_registerInfo delegate:self];

}
- (void)login:(NSDictionary *)_loginDic
{
    [AppComManager getBanBuData:BanBu_Check_Login par:_loginDic delegate:self];
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
            
            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"uploadFailNotice", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"reUpload", nil), nil];
            alert.tag = 1;
            [alert show];
            [alert release];
            return;
        }
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }

        
        return;
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
        if([[resDic valueForKey:@"ok"] boolValue])
        {

            NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
            [registerInfo setValue:[self getFacePath:[resDic valueForKey:@"smallpic"]] forKey:@"facepath"];
            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"smallpic"]] forKey:@"facefile"];
            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"largepic"]] forKey:@"facefull"];
            [self saveRegister:registerInfo];

            //弹出UIAlertView  点击确定进行登录操作
            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"waitauditNotice", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
            alert.tag = 2;
            [alert show];
            [alert release];

        }else{
            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:2.0];
        }
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Register_User]){
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"email"] forKey:@"email"];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"pass"] forKey:@"pass"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:@"plat"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:@"plong"];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"regby"] forKey:@"regby"];
            
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            [loginDic setValue:delegate.pushid forKey:@"pushid"];
            
            NSString *isJailbroken = nil;
            if([[UIDevice currentDevice] isJailbroken]){
                isJailbroken = @"YES";
            }else{
                isJailbroken = @"NO";
            }
            
            NSError *error;
            CFUUIDRef puuid = CFUUIDCreate( nil );
            CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
            NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
            CFRelease(puuid);
            CFRelease(uuidString);
            if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
            {
                [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
            }
            [result release];
            NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
            [loginDic setValue:[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID] forKey:@"sysparam"];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"osver"];
            NSString *deviceStr = [[UIDevice currentDevice] platformString];
            NSString *dev = nil;
            NSString *isp = nil;
            if([deviceStr rangeOfString:@"("].location != NSNotFound&&[deviceStr rangeOfString:@")"].location != NSNotFound)
            {
                isp = [deviceStr substringFromIndex:[deviceStr rangeOfString:@"("].location];
                dev = [deviceStr substringToIndex:[deviceStr rangeOfString:@"("].location];
            }
            //    NSLog(@"%@ %@",isp,dev);
            [dic setValue:isp forKey:@"isp"];
            [dic setValue:dev forKey:@"dev"];
            
            [dic setValue:[[UIDevice currentDevice] name] forKey:@"name"];
            [dic setValue:isJailbroken forKey:@"jail"];
            [loginDic setValue:dic forKey:@"phoneinfor"];
            
            
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
            BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            
            if(ap.pushid&&ap.pushid.length)
            {
                [loginDic setValue:ap.pushid forKey:@"deviceid"];
            }
            else
            {
                
                [loginDic setValue:systemUDID forKey:@"deviceid"];
            }

            
            NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
            [loginDic setValue:version forKey:@"version"];
            [self login:loginDic];
            self.navigationController.view.userInteractionEnabled = NO;
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"getMessage", nil) activityAnimated:YES];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:2.0];
        }
    }

    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login]){
        

        if([[resDic valueForKey:@"ok"]boolValue]){
            MyAppDataManager.loginid = [resDic valueForKey:@"loginid"];
            MyAppDataManager.useruid = [resDic valueForKey:@"userid"];
            MyAppDataManager.userAvatar =[resDic valueForKey:@"uface"];
            //创建10张聊天记录表
            [MyAppDataManager initDetailChatMessageTable];
            [UserDefaults setValue:resDic forKey:MyAppDataManager.useruid];

            if(![[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]){
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [settingsDic setValue:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil] forKey:@"boolKey"];
                [settingsDic setValue:@"msg_1" forKey:@"MusicSwith"];
                [settingsDic setValue:@"send_0" forKey:@"sendMsgBoolKey"];//添加发消息声音提示
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"systemset_friendreadstatus"];//发送消息已读状态设置
                [settingsDic setValue:[NSNumber numberWithBool:NO] forKey:@"setFollowsHidden"];//隐藏关注的人，默认为否，不隐藏

                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"visitYouNotification"];   //接收“我查看了你的个人资料”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"followYouNotification"];  //接收“我关注了你”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"takeCareNotification"];   //接收新用户注册通知
                [settingsDic setValue:[NSNumber numberWithBool:1] forKey:@"onceRun"];
                //保存当前本版号
                NSString  *versonPath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"data.dat"];
      
                NSMutableDictionary * versonDic = [NSKeyedUnarchiver unarchiveObjectWithFile:versonPath];
                NSString * versonString = MyAppDataManager.newVersionNumber;
                versonString = [versonString stringByReplacingOccurrencesOfString:@"." withString:@""];
                [versonDic setValue:versonString forKey:MyAppDataManager.useruid];
                NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:versonDic];
                [listData writeToFile:versonPath atomically:YES];
                
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            else
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            [UserDefaults setValue:MyAppDataManager.useruid forKey:@"myID"];
            [UserDefaults synchronize];            
            
            if([[MyAppDataManager.regDic valueForKey:@"regby"]isEqualToString:@"b"]){
                NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
                if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 2){
                    [pars setValue:@"twitter" forKey:@"bindto"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@,%@",[UserDefaults valueForKey:@"TAccessToken"],[UserDefaults valueForKey:@"TAccessTokenSecret"],[UserDefaults valueForKey:@"TUser"]] forKey:@"bindstring"];
                }else if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 1){
                    [pars setValue:@"facebook" forKey:@"bindto"];
                    //            [pars setValue:[NSString stringWithFormat:@"%@,%@",nil,@""] forKey:@"bindstring"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@",[UserDefaults valueForKey:@"FBAccessToken"],[UserDefaults valueForKey:@"FBUser"]] forKey:@"bindstring"];
                }
                
                
                [AppComManager getBanBuData:BanBu_Set_User_accountbind par:pars delegate:self];
                self.navigationController.view.userInteractionEnabled = NO;
            }else{
                [UserDefaults setValue:@"" forKey:@"QUser"];
                [UserDefaults setValue:@"" forKey:@"sinaUser"];
                BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.logined = YES;
                [delegate setViewController:YES];
            }
            
            
        }

    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_accountbind]){
        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
        [uidDic setValue:[resDic valueForKey:@"bindlist"] forKey:@"bindlist"];
        [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
        [UserDefaults synchronize];
        
        
        BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.logined = YES;
        [delegate setViewController:YES];
        
    }
}
-(void)changeAvatar:(UIButton *)sender
{
    [_avatorView setImageWithURL:[NSURL URLWithString:[[_facelist objectAtIndex:sender.tag-1223] valueForKey:@"system_facefile"]]];
    _useDefaultImage = YES;
    selectIndex = sender.tag-1223;
}
- (NSString *)getFacePath:(NSString *)parStr{
    NSInteger start = 7;
    NSInteger end = [parStr rangeOfString:@"/photo" options:NSBackwardsSearch].location;
    return [parStr substringWithRange:NSMakeRange(start, end-start)];
}

- (NSString *)getFaceName:(NSString *)parStr{
    NSInteger start = [parStr rangeOfString:@"face/" options:NSBackwardsSearch].location+5;
    NSInteger end = parStr.length;
    return [parStr substringWithRange:NSMakeRange(start, end-start)];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    self.imagePathExtension = nil;
}

- (void)dealloc
{
    [_imagePathExtension release],_imagePathExtension = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



//facebook分享


- (void) performPublishAction:(void (^)(void)) action {
    // we defer request for permission to post to the moment of post, then we check for the permission
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        // if we don't already have the permission, then we request it now
        [[FBSession activeSession] reauthorizeWithPublishPermissions:@[@"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
            if (!error) {
                action();
            }
        }];
    } else {
        action();
    }
}

@end
